<?php
namespace App\Controllers;

use App\Models\SelectionModel;
use CodeIgniter\API\ResponseTrait;
use App\Models\StudyLocationModel;

class Selection extends BaseController
{
    use ResponseTrait;

    // 显示表单视图
    public function index()
    {
        // $data = [
        //     'studyLocations' => [
        //         ['id' => 1, 'name' => '石燕湖公园', 'description' => '自然风光优美，适合户外探索和团队活动'],
        //         ['id' => 2, 'name' => '书堂山欧阳询文化产业园', 'description' => '感受书法文化，了解历史名人'],
        //         ['id' => 3, 'name' => '长沙世界之窗', 'description' => '主题乐园，集娱乐与文化体验于一体'],
        //         ['id' => 4, 'name' => '长沙园林生态园', 'description' => '观赏各类植物，体验生态农业'],
        //         ['id' => 5, 'name' => '湘江欢乐海洋', 'description' => '海洋主题公园，探索海洋生物']
        //     ]
        // ];
        
        $studyLocationModel = new StudyLocationModel();
        $studyLocations = $studyLocationModel->where("is_open", 1)->orderBy("location_order", "ASC")->findAll();
        $data['studyLocations'] = $studyLocations;
        
        return view('selection_form', $data);
    }
    
    public function isDifferent(string $str, string $fields, array &$data): bool
    {
        $fields = explode(',', $fields);
        foreach ($fields as $field) {
            if (isset($data[$field]) && $str === $data[$field]) {
                return false;
            }
        }
        return true;
    }
    // 处理表单提交
    public function submit()
    {
        $rules = [
            'className'    => 'required|string|in_list[五（1）班,五（2）班]',
            'student_name' => 'required|string|max_length[50]',
            'firstChoice'  => 'required|string|max_length[255]',
            'secondChoice' => [
                'label' => '第二志愿',
                'rules' => 'required|string|max_length[255]',
                'errors' => [
                    'required' => '请选择第二志愿',
                ]
            ],
            'thirdChoice' => [
                'label' => '第三志愿',
                'rules' => 'required|string|max_length[255]',
                'errors' => [
                    'required' => '请选择第三志愿',
                ]
            ],
        ];
    
        // 添加自定义验证
        $validation = \Config\Services::validation();
        $validation->setRules($rules);
    
        if (!$validation->withRequest($this->request)->run()) {
            throw new \Exception(implode(', ', $validation->getErrors()));
        }
    
        // 手动验证选项不重复
        $data = $this->request->getPost();
        if ($data['secondChoice'] === $data['firstChoice']) {
            throw new \Exception('第二志愿不能与第一志愿相同');
        }
    
        if ($data['thirdChoice'] === $data['firstChoice'] || $data['thirdChoice'] === $data['secondChoice']) {
            throw new \Exception('第三志愿不能与第一或第二志愿相同');
        }
    
        $model = new SelectionModel();
    
        // 检查相同班级和姓名的记录是否已存在
        $existingRecord = $model->where([
            'class_name' => $data['className'],
            'student_name' => $data['student_name']
        ])->first();
    
        if ($existingRecord) {
            $message = "{$data['className']} 的 {$data['student_name']} 已提交记录";
            return $this->respond([
                'status'  => 'error',
                'message' => $message
            ], 400);
        }
    
        $data = [
            'class_name'         => $this->request->getPost('className'),
            'student_name'  => $this->request->getPost('student_name'),
            'first_choice'  => $this->request->getPost('firstChoice'),
            'second_choice' => $this->request->getPost('secondChoice'),
            'third_choice'  => $this->request->getPost('thirdChoice'),
        ];
    
        // 保存数据
        try {
            $model->insert($data);
            return $this->respond([
                'status'       => 'success',
                'message'      => '提交成功',
                'className'        => $data['class_name'],
                'student_name' => $data['student_name'],
                'firstChoice'  => $data['first_choice'],
                'secondChoice' => $data['second_choice'],
                'thirdChoice'  => $data['third_choice']
            ], 201);
        } catch (\Exception $e) {
            log_message('error', '表单提交错误: '. $e->getMessage());
            return $this->respond([
              'status'  => 'error',
              'message' => '提交失败: '. $e->getMessage()
            ], 500);
        }
    }
}